﻿using System.Xml;
using System;

namespace Bridge.Exporter.Utilities
{
    /// <summary>
    /// Helps with using the XmlWriter.
    /// </summary>
    public static class XmlWriterExtensions
    {
        /// <summary>
        /// Writes a key value pair to the <see cref="XmlWriter"/>.
        /// </summary>
        /// <param name="self"><see cref="XmlWriter"/> to write to.</param>
        /// <param name="key">Name of the key.</param>
        /// <param name="value">Object value.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="self"/>, <paramref name="key"/> or <paramref name="value"/> is null.</exception>
        /// <exception cref="ArgumentException">Thrown if <paramref name="self"/> is empty.</exception>
        /// <exception cref="InvalidOperationException">Thrown if <paramref name="self"/> is closed or in error state.</exception>
        public static void WriteKeyValuePair(this XmlWriter self, string key, object value)
        {
            if (self == null) throw new ArgumentNullException("self");
            if (key == null) throw new ArgumentNullException("key");
            if (value == null) throw new ArgumentNullException("value");
            if (key.Length == 0) throw new ArgumentException("key cannot be empty", "key");
            if (self.WriteState == WriteState.Closed) throw new InvalidOperationException("XmlWriter is closed.");
            if (self.WriteState == WriteState.Error) throw new InvalidOperationException("XmlWriter is in an error state.");

            self.WriteStartElement(key);
            self.WriteValue(value.ToString());
            self.WriteEndElement();
        }
    }
}
